package com.blogsoho.taurus.interceptors;

import com.blogsoho.taurus.services.UserService;
import com.blogsoho.taurus.services.impl.UserServiceImpl;
import com.blogsoho.taurus.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2017/6/5.
 */
public class CommonInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Bean("userService")
    public UserService userService() {
        return new UserServiceImpl();
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        httpServletRequest.setAttribute("currUserName", name);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            Map<String, Object> model = modelAndView.getModel();
            model.put("baseContext", httpServletRequest.getRequestURI());

            //处理用户信息
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String name = auth.getName();
            if (auth.isAuthenticated() && !"anonymousUser".equalsIgnoreCase(name)) {

                UserVO user = userService.getUserByName(name).getData();
                String role = null;
                List<GrantedAuthority> authorities = (List<GrantedAuthority>) auth.getAuthorities();
                if (authorities != null && authorities.size() > 0) {
                    role = authorities.get(0).getAuthority();
                }
                role = StringUtils.isEmpty(role) ? "USER" : role.toUpperCase();

                model.put("user", user);
                model.put("userRole", role);
            }

        }

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

    }
}
